import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
import ZImg from 'react-zmage';
import 'react-zmage/lib/zmage.css'
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, leaveStatue } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';
import AddOrEditReserve from './../CarInfo/addOrEditReserve';
import request from '@/utils/request';
import AddOrEditReserve2 from '../CarInfo/addOrEditReserve2';
import CarPeriods from './../CarReserve/carPeriods';
import mail from '../../images/mail.png';
import mailOpen from '../../images/mail-open.png';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ car_replicator, loading, global }) => ({
  car_replicator,
  global,
  loading: loading.models.car_replicator,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      users: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      car_replicator: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        car_replicator: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'car_replicator/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'car_replicator/changeLoaded',
          });
          dispatch({
            type: 'car_replicator/changeTableY',
          });
        },
      });

    }
    const that = this;
    // request(`/users`, {
    //   method: 'GET',
    //   params: {
    //     inspector: 1,
    //     per_page: 100,
    //   },
    // }).then((response) => {
    //   if (response.status === 200) {
    //     that.setState({
    //       users: response.data.data,
    //     });
    //   }
    //
    // });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'car_replicator/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'car_replicator/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'car_replicator/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      car_replicator: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>
          <FormItem label="车牌号">
            {getFieldDecorator('license_plate_number', {
              initialValue: searchParams.license_plate_number,
            })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
          </FormItem>

          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'car_replicator/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('添加车辆成功');
        that.setState({
          addModal: false,
        });
        const {
          car_replicator: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      license_plate_number: '',
      inspector_id: '',
      device_number: '',
      status: '',
      page: 1,
      per_page: 30,
    });
  };

  handleReserve = () => {
    const formValues = this.ReserveForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const state = this.ReserveForm.state;
    console.log('start', state.start);
    console.log('end', state.end);
    let reviewer_ids = [];
    let replicator_ids = [];
    formValues.reviewer_ids.forEach(item => {
      reviewer_ids.push(item.key.split('#')[0]);
    });
    formValues.replicator_ids.forEach(item => {
      replicator_ids.push(item.key.split('#')[0]);
    });
    const that = this;
    request(`/car_applications/${this.state.editRecord.id}`, {
      method: 'PUT',
      data: {
        cause: formValues.cause,
        reviewer_ids, replicator_ids,
        start_time: state.start,
        end_time: state.end,
      },
    }).then((response) => {
      if (response.status === 200) {
        message.success('修改预定车辆成功');
        that.setState({
          reserveModal: false,
        });
        const {
          car_replicator: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }

    });

  };

  handleCancel = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `car_replicator/cancelIssue`,
      payload: { id },
      callback: () => {
        message.success('取消车辆成功');
        const {
          car_replicator: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `car_replicator/remove`,
      payload: { id },
      callback: () => {
        message.success('删除车辆成功');
        const {
          car_replicator: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleUpload=(type,id)=>{
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `car_replicator/${type}`,
      payload: { id },
      callback: () => {
        message.success(`${type==='submit'?'提交':'取消'}用车成功`);
        const {
          car_replicator: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  }
  render() {
    const that = this;
    const {
      car_replicator: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '',
        width: 40,
        key: '_index2',
        frozen: true,
        formatter: (event) => {
          const is_read=find(event.row.replicators,function(o) {
            return o.name===sessionStorage.getItem('username')
          }).status;
          return <img style={{width:'24px'}} src={is_read===1?mail:mailOpen} alt=""/>
        },
      },
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            car_replicator: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '车辆照片',
        width: 150,
        frozen: true,
        key: 'image_path',
        formatter: (event) => {
          return event.row.car.image_path ? <ZImg style={{ height: '80px' }}
                                                  src={event.row.car.image_path}/> : '';
        },
      },
      {
        name: '车辆所属部门',
        width: 120,
        frozen: true,
        key: 'department_name',
      },
      {
        name: '司机',
        width: 100,
        frozen: true,
        key: 'driver',
      },
      {
        name: '车牌号',
        width: 100,
        frozen: true,
        key: 'license_plate_number',
        formatter: (event) => {
          return event.row.car.license_plate_number;
        },
      },
      {
        name: '审批状态',
        key: 'status',
        width: 100,
        frozen: true,
        formatter: (event) => {
          return leaveStatue(event.value);
        },
      },
      {
        name: '品牌',
        key: 'brand',
        width: 80,
        formatter: (event) => {
          return event.row.car.brand;
        },
      },
      {
        name: '车辆类型',
        width: 70,
        key: 'type',
        formatter: (event) => {
          return event.row.car.type;
        },
      },
      {
        name: '乘坐人数',
        width: 70,
        key: 'passenger_count',
        formatter: (event) => {
          return event.row.car.passenger_count;
        },
      },
      {
        name: '申请部门',
        key: 'department_name2',
        width: 100,
        formatter: (event) => {
          return event.row.user.department_name;
        },
      },
      {
        name: '申请人',
        key: 'name',
        width: 100,
        formatter: (event) => {
          return event.row.user.name;
        },
      },
      {
        name: '提交时间',
        key: 'submit_time',
        width: 150,
      },
      {
        name: '事由',
        key: 'cause',
        width: 160,
      },
      {
        name: '开始时间',
        key: 'start_time',
        width: 150,
      },
      {
        name: '结束时间',
        key: 'end_time',
        width: 150,
      },
      {
        name: '操作',
        width: 100,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                detailModal: true,
              });
              const is_read=find(event.row.replicators,function(o) {
                return o.name===sessionStorage.getItem('username')
              }).status;
              if(is_read===1){
                const { dispatch } = this.props;
                dispatch({
                  type: `car_replicator/read`,
                  payload: { id:event.row.id,status:2 },
                  callback: () => {
                    const {
                      car_replicator: { searchParams },
                    } = that.props;
                    that.handleSearch(searchParams);
                  },
                });
              }
            }
            }
          >详情
          </Button>

        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>车辆抄送</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            headerRowHeight={35}
            rowHeight={100}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'car_replicator/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>

      <Modal
        title={<BuildModalTitle visible={this.state.detailModal} modalClass="detailModal"
                                title={`${this.state.editRecord.car ?
                                  this.state.editRecord.car.license_plate_number : ''} 用车详情`}/>}
        destroyOnClose
        visible={this.state.detailModal}
        centered
        className="detailModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={1000}
        onOk={() => {
          this.setState({ detailModal: false, editRecord: {} });
        }}
        footer={null}
        onCancel={() => {
          this.setState({ detailModal: false, editRecord: {} });
        }}
      >
        <CarPeriods save={()=>{
          message.success('操作成功');
          const {
            car_replicator: { searchParams },
          } = that.props;
          that.handleSearch(searchParams);
          this.setState({ detailModal: false, editRecord: {} });

        }}  editRecord={this.state.editRecord} wrappedComponentRef={(inst) => this.EditForm = inst}/>
      </Modal>
    </div>;
  }
}

export default BasicList;
